const mysql = require('../db/mysql57');
const minio = require('../db/minio');

const userDao = {
    getUserInfo(uid) {
        let sql = `select
                u.id as id,
                u.username as username,
                u.userTypeId as userTypeId,
                ut.name as userType,
                u.sex as sex,
                u.bio as bio,
                u.grade as grade,
                u.college as college,
                u.subCollege as subCollege,
                u.major as major
            from User as u
            left join UserType as ut on u.userTypeId = ut.id
            where u.id = ? limit 1`;
        let data = [ uid ];
        return mysql.sqlExec(sql, data);
    },
    updateUserInfo(uid, sex, grade, college, subCollege, major, username, bio) {
        let sql = `update User set sex = ?, grade = ?, college = ?, subCollege = ?, major = ?, username = ?, bio = ?, isNewUser = ? where id = ?`;
        let data = [ sex, grade, college, subCollege, major, username, bio, 'false', uid ];
        return mysql.sqlExec(sql, data);
    },
    followCount(uid) {
        let sql = `select
            (
                select count(1) from UserLike where uid = ?
            ) as followCount,
            (
                select count(1) from UserLike where likeedId = ?
            ) as beFollowCount`;
        let data = [ uid, uid ];
        return mysql.sqlExec(sql, data);
    },
    follow(uid, followuid, is_like) {
        let sql;
        let data;
        if (is_like) {
            sql = `insert into UserLike(uid, likeedId) (
                    select ?, ? where not exists (
                        select 1 from UserLike where uid = ? and likeedId = ?
                    )
                )`;
            data = [ uid, followuid, uid, followuid ];
        } else {
            sql = `delete from UserLike where uid = ? and likeedId = ?`;
            data = [ uid, followuid ];
        }
        return mysql.sqlExec(sql, data);
    },
    getFollowList(uid, cursor, limit) {
        let sql, data;
        if (cursor) {
            sql = `select
                    ul.id as id,
                    u.id as uid,
                    u.username as name
                from UserLike as ul
                left join User as u on ul.likeedId = u.id
                where ul.uid = ? and ul.id <= ?
                order by ul.id desc
                limit ?`;
            data = [ uid, cursor, limit + 1 ];
        } else {
            sql = `select
                    ul.id as id,
                    u.id as uid,
                    u.username as name
                from UserLike as ul
                left join User as u on ul.likeedId = u.id
                where ul.uid = ?
                order by ul.id desc
                limit ?`;
            data = [ uid, limit + 1 ];
        }
        return mysql.sqlExec(sql, data);
    },
    getFansList(uid, cursor, limit) {
        let sql, data;
        if (cursor) {
            sql = `select
                    ul.id as id,
                    u.id as uid,
                    u.username as name,
                    (select count(1) from UserLike where uid = ul.likeedId and likeedId = ul.uid) as status
                from UserLike as ul
                left join User as u on ul.uid = u.id
                where ul.likeedId = ? and ul.id <= ?
                order by ul.id desc
                limit ?`;
            data = [ uid, cursor, limit + 1 ];
        } else {
            sql = `select
                    ul.id as id,
                    u.id as uid,
                    u.username as name,
                    (select count(1) from UserLike where uid = ul.likeedId and likeedId = ul.uid) as status
                from UserLike as ul
                left join User as u on ul.uid = u.id
                where ul.likeedId = ?
                order by ul.id desc
                limit ?`;
            data = [ uid, limit + 1 ];
        }
        return mysql.sqlExec(sql, data);
    },
    async uploadAvatar(uid, buffer) {
        // 尝试开启事务
        let connection;
        let result;
        let browser = 'xlsd-avatar';
        let uri = '';
        let imgId;
        let ret;
        // 开启事务
        try {
            connection = await mysql.startTransaction();
        } catch (error) {
            throw error;
        }
        try {
            // 往 Avatar 表中插入数据
            let sql = `insert into Avatar (browser, uri, status) VALUES (?, ?, ?)`;
            let data = [ browser, '', '待上传' ];
            result = await mysql.sqlExecInTransaction(connection, sql, data);
            imgId = result.insertId;
            uri = `${imgId}.jpg`;
            // 更新 mysql 数据库中 图片的上传状态
            sql = `update Avatar set status = ?, uri = ? where id = ?`;
            data = [ '已完成', uri, imgId ];
            await mysql.sqlExecInTransaction(connection, sql, data);
            // 更新用户表中的头像id
            sql = `update User set avatarId = ? where id = ?`;
            data = [ imgId, uid ];
            result = await mysql.sqlExecInTransaction(connection, sql, data);
        } catch (err) {
            await mysql.rollbackTransaction(connection);
            throw err;
        }
        // 往 MinIO 中上传图片（这个操作应该要封装到 minio 驱动里，后续修改）
        try {
            await new Promise((resolve, reject) => {
                minio.minio.putObject(browser, uri, buffer, buffer.length, async function (err, etag) {
                    if (err) {
                        reject(err);
                        return ;
                    } else {
                        resolve(true);
                    }
                });
            });
        } catch (err) {
            await mysql.rollbackTransaction(connection);
            throw err;
        }
        // 提交事务
        try {
            mysql.commitTransaction(connection);
        } catch (error) {
            await mysql.rollbackTransaction(connection);
            throw error;
        }
        // 返回数据
        return ret;
    }
};

module.exports = userDao;